package com.yuandian.customer.perception.controller;

import com.yuandian.api.customer_perception.po.SystemAnalysisParams;
import com.yuandian.api.customer_perception.po.SystemCompareTrendParams;
import com.yuandian.api.customer_perception.po.WeekdayParams;
import com.yuandian.api.customer_perception.vo.SystemCompareTrendVo;
import com.yuandian.api.customer_perception.vo.Weekday;
import com.yuandian.api.management.feign.RemoteWeekDaysService;
import com.yuandian.bpm.common.core.constant.CommonConstants;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.customer.perception.service.ISystemAnalysisService;
import com.yuandian.po.BaseSearch;
import com.yuandian.utils.YDateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.*;

/**
 * 说明：系统分析controller
 * @Author yanjun
 * @Date 2021/8/11 13:33
 */
@RestController
@Api(value = "系统分析接口", tags = "系统分析接口")
@RequestMapping("/system/analysis")
@Slf4j
public class SystemAnalysisController {

    @Autowired
    private ISystemAnalysisService systemAnalysisService;

	@Autowired
	private RemoteWeekDaysService remoteWeekDaysService;


    /**
     * 查询系统分析概况
     * @param params 系统分析请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "系统分析-查询系统分析概况", notes = "系统分析-查询系统分析概况")
	@GetMapping("/querySystemAnalysisOverview")
    public R<Object> querySystemAnalysisOverview(SystemAnalysisParams params) {
        return systemAnalysisService.querySystemAnalysisOverview(params);
    }


    /**
     * 查询系统告警占比
     * @param params 系统分析请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "系统分析-查询业务告警占比", notes = "系统分析-查询业务告警占比")
	@GetMapping("/querySystemAlarmProportion")
    public R<Object> querySystemAlarmProportion(SystemAnalysisParams params) {
        return systemAnalysisService.querySystemAlarmProportion(params);
    }


    /**
     * 查询系统指标趋势
     * 系统健康度,平均响应时长,系统请求量--usi_sys_detail_stat_m-KhgzBusinessDetailStatTask-系统指标趋势-延迟3分钟-/api-khgz/system/analysis/querySystemIndicatorTrend
     * @param params 系统分析请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "系统分析-查询系统指标趋势 系统健康度,平均响应时长,系统请求量", notes = "系统分析-查询系统指标趋势 系统健康度,平均响应时长,系统请求量")
	@PostMapping("/querySystemIndicatorTrend")
    public R<Object> querySystemIndicatorTrend(@RequestBody SystemAnalysisParams params) {
        return systemAnalysisService.querySystemIndicatorTrend(params);
    }


    /**
     * 查询系统对比趋势
     * 受理量对比趋势--usi_sys_detail_stat_m-KhgzBusinessDetailStatTask-系统对比趋势-延迟3分钟-/api-khgz/modules/system/analysis/querySystemCompareTrend
     * @param params 系统对比趋势请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "系统分析-查询系统对比趋势 受理量对比趋势", notes = "系统分析-查询系统对比趋势 受理量对比趋势")
	@PostMapping("/querySystemCompareTrend")
    public R<Object> querySystemCompareTrend(@RequestBody SystemCompareTrendParams params) throws ParseException {
        R<Object> result = systemAnalysisService.querySystemCompareTrend(params);

        // timeCycle为2时，去除节假日的数据点
        if (params.getTimeCycle() != null&&params.getTimeCycle() == 2){
            List<BaseSearch> baseSearches = params.getTimeRangeGroup();
            // 循环趋势图数组
            Map<Integer, List<SystemCompareTrendVo>> resultMap = (Map<Integer, List<SystemCompareTrendVo>>) result.getData();
            for (int i = 0;i<baseSearches.size();i++){
                List<SystemCompareTrendVo> list = resultMap.get(i+1);

                String startTime = baseSearches.get(i).getStartTime();
                String endTime = baseSearches.get(i).getEndTime();
                // 如果结束时间大于当前时间，则使用当前时间
                if (YDateUtil.parse(endTime, YDateUtil.YYYY_MM_DD_HH_MM_SS).getTime() > new Date().getTime()){
                    endTime = YDateUtil.parseDateToStr(YDateUtil.YYYY_MM_DD,new Date())+" 00:00:00";
                }
                WeekdayParams weekdayParams = new WeekdayParams();
                weekdayParams.setStartTime(startTime);
                weekdayParams.setEndTime(endTime);
                weekdayParams.setType(2);
                R<List<Weekday>> listR = remoteWeekDaysService.queryNoPageWeekday(weekdayParams);
                List<Weekday> weekdayList = listR.getData();
                int code = listR.getCode();
                if (code == CommonConstants.FAIL) {
                    log.error("远程调用配置系统获取获取节假日数据失败，错误：{}", listR.getMsg());
                }
                weekdayParams.setType(1);
                R<List<Weekday>> listR1 = remoteWeekDaysService.queryNoPageWeekday(weekdayParams);
                code = listR1.getCode();
                if (code == CommonConstants.FAIL) {
                    log.error("远程调用配置系统获取获取工作日数据失败，错误：{}", listR.getMsg());
                }
                List<Weekday> workdayList = listR1.getData();
                List<String> weekdays = new ArrayList<>();
                List<String> workdays = new ArrayList<>();
                for (Weekday weekday : weekdayList) {
                    weekdays.add(weekday.getDay());
                }
                for (Weekday workday : workdayList) {
                    workdays.add(workday.getDay());
                }

                for (int j = 0; j <list.size() ; j++) {
                    SystemCompareTrendVo systemCompareTrendVo = list.get(j);
                    String cycleTime = systemCompareTrendVo.getCycleTime().replace(" 00:00:00.0","");
                    if (weekdays.contains(cycleTime)){
                        SystemCompareTrendVo systemCompareTrendVo1 = list.get(j);
                        systemCompareTrendVo1.setCompleteCount("-");
                    }
                }
                HashMap<String,SystemCompareTrendVo> hashMap = new HashMap<>();
                list.forEach(systemCompareTrendVo->{
                    hashMap.put(systemCompareTrendVo.getCycleTime().replace(" 00:00:00.0",""),systemCompareTrendVo);
                });

                // 拼接假期数据
                weekdays.forEach(s -> {
                    if (!hashMap.containsKey(s)){
                        SystemCompareTrendVo systemCompareTrendVo = new SystemCompareTrendVo();
                        systemCompareTrendVo.setCycleTime(s+"  00:00:00.0");
                        systemCompareTrendVo.setCompleteCount("-");
                        list.add(systemCompareTrendVo);
                    }
                });
                // 拼接工作日数据
                workdays.forEach(s->{
                    if (!hashMap.containsKey(s)){
                        SystemCompareTrendVo systemCompareTrendVo = new SystemCompareTrendVo();
                        systemCompareTrendVo.setCycleTime(s+"  00:00:00.0");
                        systemCompareTrendVo.setCompleteCount("0");
                        list.add(systemCompareTrendVo);
                    }
                });
            }

        }
        return result;
    }


    /**
     * 分页查询系统业务总览
     * @param params 系统分析请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "系统分析-分页查询系统业务总览", notes = "系统分析-分页查询系统业务总览")
	@GetMapping("/querySystemBusinessOverview")
    public R<Object> querySystemBusinessOverview(SystemAnalysisParams params) {
        return systemAnalysisService.querySystemBusinessOverview(params);
    }


    /**
     * 导出系统业务总览列表
     * @param params 系统分析请求参数
     * @param response 响应上下文
     */
	@ApiOperation(value = "系统分析-导出系统业务总览列表", notes = "系统分析-导出系统业务总览列表")
	@GetMapping("/exportSystemBusinessOverview")
    public void exportSystemBusinessOverview(SystemAnalysisParams params, HttpServletResponse response) {
        try {
            systemAnalysisService.exportSystemBusinessOverview(params, response);
        } catch (Exception e) {
            e.printStackTrace();
//             ResponseUtil.setResponseResult(Result
//                     .setFail(ApiResultCode.EXPORT_EXCEL_ERROR.getCode(), ApiResultCode.EXPORT_EXCEL_ERROR.getMsg()), response);
        }
    }


    /**
     * 查询业务指标TOPN
     * @param params 系统分析请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "系统分析-查询业务指标TOPN", notes = "系统分析-查询业务指标TOPN")
	@GetMapping("/queryBusinessIndicatorTopN")
    public R<Object> queryBusinessIndicatorTopN(SystemAnalysisParams params) {
        return systemAnalysisService.queryBusinessIndicatorTopN(params);
    }


    /**
     * 分页查询系统操作员总览
     * @param params 系统分析请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "系统分析-分页查询系统操作员总览", notes = "系统分析-分页查询系统操作员总览")
	@GetMapping("/querySystemOperatorOverview")
    public R<Object> querySystemOperatorOverview(SystemAnalysisParams params) {
        return systemAnalysisService.querySystemOperatorOverview(params);
    }


    /**
     * 导出系统操作员总览列表
     * @param params 系统分析请求参数
     * @param response 响应上下文
     */
	@ApiOperation(value = "系统分析-导出系统操作员总览列表", notes = "系统分析-导出系统操作员总览列表")
	@GetMapping("/exportSystemOperatorOverview")
    public void exportSystemOperatorOverview(SystemAnalysisParams params, HttpServletResponse response) {
        try {
            systemAnalysisService.exportSystemOperatorOverview(params, response);
        } catch (Exception e) {
            e.printStackTrace();
//             ResponseUtil.setResponseResult(Result
//                     .setFail(ApiResultCode.EXPORT_EXCEL_ERROR.getCode(), ApiResultCode.EXPORT_EXCEL_ERROR.getMsg()), response);
        }
    }


    /**
     * 查询操作员业务办理量TOPN
     * @param params 系统分析请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "系统分析-查询操作员业务办理量TOPN", notes = "系统分析-查询操作员业务办理量TOPN")
	@GetMapping("/queryOperatorCompleteTopN")
    public R<Object> queryOperatorCompleteTopN(SystemAnalysisParams params) {
        return systemAnalysisService.queryOperatorCompleteTopN(params);
    }


    /**
     * 查询营业员业务办理失败分布
     * @param params 系统分析请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "系统分析-查询营业员业务办理失败分布", notes = "系统分析-查询营业员业务办理失败分布")
	@GetMapping("/queryOperatorFailBusiness")
    public R<Object> queryOperatorFailBusiness(SystemAnalysisParams params) {
        return systemAnalysisService.queryOperatorFailBusiness(params);
    }


    /**
     * 查询营业员办理业务告警类型分布
     * @param params 系统分析请求参数
     * @return 通用返回对象
     */
	@ApiOperation(value = "系统分析-查询营业员办理业务告警类型分布", notes = "系统分析-查询营业员办理业务告警类型分布")
	@GetMapping("/queryOperatorBusinessAlarm")
    public R<Object> queryOperatorBusinessAlarm(SystemAnalysisParams params) {
        return systemAnalysisService.queryOperatorBusinessAlarm(params);
    }
}
